# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

import coin.exchange.base.kr_rest.native_public_client_base as npubcb
import coin.exchange.okex_futures.kr_rest.constants as exchange_constants


class OkexFuturesNativePublicClient(npubcb.NativePublicClientBase):
  def __init__(self, timeout=3):
    npubcb.NativePublicClientBase.__init__(self, url="https://www.okex.com/api/v1", timeout=timeout)
    self._valid_contract_type = ['this_week', 'next_week', 'quarter']
    self._valid_kline_period = ['1min', '3min', '5min', '15min', '30min', \
      '1day', '3day', '1week', '1hour', '2hour', '4hour', '6hour', '12hour']

  def check_contract_type(self, contract_type):
    assert contract_type in self._valid_contract_type, \
        'Invalid contract type!'

  def check_kline_period(self, kline_period):
    assert kline_period in self._valid_kline_period, \
        'Invalid kline period!'

  def get_ticker(self, symbol, contract_type):
    self.check_contract_type(contract_type)
    url = "future_ticker.do"
    params = {
        "symbol": symbol,
        "contract_type": contract_type,
    }
    update = self._get_as_json(url, params)
    return update

  def get_orderbook(self, symbol, contract_type, size=5, merge=1):
    self.check_contract_type(contract_type)
    url = "future_depth.do"
    assert 1 <= size <= 200, 'Invalid size.'
    params = {
        'symbol': symbol,
        'contract_type': contract_type,
        'size': size,
        'merge': merge,
    }
    update = self._get_as_json(url, params)
    return update

  def get_futures_index(self, symbol):
    url = "future_index.do"
    update = self._get_as_json(url, params=dict(symbol=symbol))
    return update

  def get_history_kline(self, symbol, kline_period, contract_type, size, since=None):
    self.check_kline_period(kline_period)
    self.check_contract_type(contract_type)
    url = "future_kline.do"
    params = {
        'symbol': symbol,
        'type': kline_period,
        'contract_type': contract_type,
        'size': size,
    }
    if since:
      params['since'] = since
    update = self._get_as_json(url, params)
    return update

  def queryAll(self):
    for symbol in exchange_constants.symbol_list:
      for contract_type in exchange_constants.contract_type_list:
        print(self.get_orderbook(symbol, contract_type))


if __name__ == "__main__":
  client = OkexFuturesNativePublicClient()
  print(client.get_ticker('btc_usd', 'this_week'))
  print(client.get_orderbook('btc_usd', 'this_week'))
  print(client.get_futures_index('btc_usd'))
  client.queryAll()
  print(client.get_history_kline('btc_usd', '1hour', 'this_week', 10))
